<template>
  <div class="article-container">
    <el-row>

      <el-col :span="22" :offset="1">
        <!--列表卡片-->
        <card class="table-container" cardName="轮播图列表" :scalable="false">

          <!--工具栏-->
          <tool-bar slot="tool" @receiveKeyword="receiveKeyword" @emptyQuery="emptyQuery" class="toolbar">
            <div slot="buttonContainer" class="button-all-container">
              <!--工具栏上第一个按钮-->
              <div class="btn-container" v-if="hasPermission('carousel:insert')">
                <el-button class="toolbar-button" @click="openSaveImageModal">
                  <i class="el-icon-circle-plus-outline"></i>
                  新增图片
                </el-button>
              </div>
              <!--工具栏上第二个按钮-->
              <div class="btn-container" v-if="hasPermission('carousel:saveConfig')">
                <el-button class="toolbar-button" @click="openConfigModal">
                  <i class="iconfont icon-icon-test"></i>
                  配置信息
                </el-button>
              </div>
              <!--工具栏上第三个按钮-->
              <div class="btn-container" v-if="hasPermission('carousel:delete')">
                <el-button class="toolbar-button" @click="deleteMultiImages">
                  <i class="iconfont icon-shanchu"></i>
                  批量删除
                </el-button>
              </div>
            </div>
          </tool-bar>

          <!--卡片里的内容-->
          <el-table
            slot="content"
            ref="tagTable"
            :data="imageList"
            stripe
            border
            :fit="true"
            style="width: 100%"
            @select="selectImage"
            @select-all="selectImage"
            :key="tableKey">
            <el-table-column
              align="center"
              type="selection"
              min-width="30">
            </el-table-column>
            <el-table-column
              prop="articleTitle"
              label="文章标题"
              min-width="200">
              <template slot-scope="slot">
                <el-link
                  type="default"
                  :href="slot.row.articleLink"
                  target="_blank">
                  {{slot.row.articleTitle}}
                </el-link>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="picUrl"
              label="图片预览"
              min-width="80">
              <template slot-scope="slot">
                <el-image
                  style="width: 150px; height: 107px"
                  :src="slot.row.picUrl"
                  fit="contain"></el-image>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="sort"
              label="排序"
              min-width="30">
            </el-table-column>
            <el-table-column
              align="center"
              prop="usable"
              label="启用"
              min-width="40">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.usable"
                  active-color="#409EFF"
                  :active-value="1"
                  :inactive-value="0"
                  :disabled="!hasPermission('carousel:update')"
                  @change="changeUsable(scope.row)">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column
              prop="updateTime"
              label="更新时间"
              min-width="70">
            </el-table-column>
            <el-table-column
              prop="expireTime"
              label="过期时间"
              min-width="70">
            </el-table-column>
            <el-table-column
              label="操作"
              min-width="80">
              <template slot-scope="scope">
                <span v-if="!hasPermission('carousel:update') && !hasPermission('carousel:delete')">-</span>
                <el-button
                  type="primary"
                  class="editBtn"
                  size="small"
                  v-if="hasPermission('carousel:update')"
                  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                  size="small"
                  type="danger"
                  v-if="hasPermission('carousel:delete')"
                  @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </card>
      </el-col>
    </el-row>
    <pagination @getCurrentPage="getCurrentPageFromPagination" :total="total"></pagination>
    <config-template
      ref="configTemplate"></config-template>
  </div>
</template>

<script>

  import Card from 'components/common/card/Card';
  import ToolBar from 'components/content/toolbar/ToolBar';
  import Pagination from 'components/common/pagination/Pagination';
  import ConfigTemplate from './subView/ConfigTemplate';
  import SaveImageTemplate from './subView/SaveImageView';

  import {PORTAL_SERVER_URL, IMAGE_SERVER_URL, PATH_PORTAL_PLACEHOLDER} from "../../common/const";
  import {getImagesByPage, changeUsable, deleteByIds} from "../../network/viewsRequest/carousel";
  import {hasPermission} from "../../common/permission";

  export default {
    name: "CarouselView",
    data() {
      return {
        query: {
          currentPage: 1,
          pageSize: 10,
          keyword: '', // toolbar中传递过来的搜索关键字
        },
        imageList: [],
        total: 0,
        multiSelections: [],
        tagForUpdate: {}, // 回显时传递给模态框的标签信息
        intervalToConfigModal: null,
        maxNumToConfigModal: null
      }
    },
    computed: {
      tableKey() {
        let key = '';
        for (let i = 0; i < this.imageList.length; i++) {
          key += this.imageList[i].updateTime;
        }
        return key;
      }
    },
    components: {
      Card,
      ToolBar,
      Pagination,
      ConfigTemplate,
      SaveImageTemplate
    },
    methods: {
      hasPermission(permission) {
        return hasPermission(permission);
      },
      /**
       * 清空查询条件
       */
      emptyQuery() {
        this.query = {
          currentPage: 1,
            pageSize: 10,
            keyword: '',
        };
        this.loadTableForImage();
      },
      /**
       * 接收搜索关键字
       */
      receiveKeyword(keyword) {
        this.query.keyword = keyword;
        this.query.currentPage = 1;
        this.loadTableForImage();
      },
      /**
       * 点击多选框调用的方法
       * @param 当前已经选择的所有行的信息
       * @param 当前选择的行的信息
       */
      selectImage(selection, row) {
        this.multiSelections = selection;
      },
      /**
       * 从分页组件中接收用户点击的是哪一页
       * @param page 点击的页码
       */
      getCurrentPageFromPagination(page) {
        this.query.currentPage = page;
        // 重新加载数据
        this.loadTableForImage();
      },
      /**
       * 用户点击修改按钮所调用的方法
       * @param index 该条数据的索引
       * @param row 该条数据的完整信息
       */
      handleEdit(index, row) {
        this.$router.push("/dashboard/carousel/saveimage?id=" + row.id);
      },
      /**
       * 用户点击删除按钮所调用的方法
       * @param index 该条数据的索引
       * @param row 该条数据的完整信息
       */
      handleDelete(index, row) {
        let delIds = [];
        delIds.push(row.id);
        this.deleteIdsLogic(delIds);
      },
      /**
       * 批量删除图片
       */
      deleteMultiImages() {
        // 1.校验
        if (this.multiSelections.length == 0) {
          this.$message.error("请先选择需要操作的记录！");
          return;
        }
        // 2.删除
        let delIds = this.multiSelections.map(item => {
          return item.id;
        })
        this.deleteIdsLogic(delIds);
      },
      /**
       * 删除操作的具体逻辑
       */
      deleteIdsLogic(ids) {
        this.$confirm("是否确定要删除？", "警告", {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: "warning"
        }).then(() => {
          deleteByIds(ids.join()).then(res => {
            if (res.code == 1) {
              this.$message.success("删除成功！");
              this.loadTableForImage();
            } else {
              this.$message.error(res.message);
            }
          })
        }).catch(() => {
          this.$message.info("删除操作已经被取消");
        })
      },
      /**
       * 点击新增按钮调用的方法
       */
      openSaveImageModal() {
        this.$router.push("/dashboard/carousel/saveimage");
      },
      /**
       * 点击配置信息按钮调用的方法
       */
      // TODO 能否将all方法提取到request.js中
      openConfigModal() {
        // 打开窗口
        this.$refs.configTemplate.show();
      },
      /**
       * 修改是否启用
       */
      changeUsable(row) {
        changeUsable(row.id, row.usable).then(res => {
          if (res.code == 1) {
            this.$message({
              type: "success",
              message: '操作成功！'
            });
          } else {
            this.$message({
              type: "error",
              message: res.message
            });
            // 失败的时候刷新，显示为原来的状态
            this.loadTableForImage();
          }

        })
      },
      /**
       * 加载页面数据
       */
      loadTableForImage() {
        getImagesByPage(this.query).then(res => {
          console.log(res);
          if (res.code == 1) {
            let raw = res.data.items;
            let imageList = raw.map(item => {
              // 处理图片链接
              // item.picUrl = IMAGE_SERVER_URL + item.picUrl;

              // 处理文章链接
              if (item.articleLink.indexOf(PATH_PORTAL_PLACEHOLDER) > -1) {
                item.articleLink = PORTAL_SERVER_URL + item.articleLink.substring(PATH_PORTAL_PLACEHOLDER.length);
              }
              return item;
            });
            this.imageList = imageList;
            this.total = res.data.total;
          } else {
            this.imageList = [];
            this.total = 0;
          }

        })
      }
    },
    mounted() {
      this.loadTableForImage();
    }
  }
</script>

<style scoped>
  .toolbar-button {
    width: 120px;
    height: 36px;
    padding: 0 20px 0 15px;
    vertical-align: middle;
  }
  .table-container {
    width: 100%;
    height: 100%;
    position: relative;
  }
  .btn-container {
    margin-right: 5px;
  }
  .el-card {
    margin-top: 30px;
  }
  .editBtn {
    background-color: #409EFF;
    border: 1px solid #409EFF;
    color: #fff
  }
  .tag-disabled {
    cursor: not-allowed;
  }
  .button-all-container, .custom-container {
    display: inline-block;
    vertical-align: bottom;
  }
  .el-select {
    width: 150px !important;
    height: 36px !important;
    margin-left: 10px;
  }
</style>

<style>
  .el-input__inner {
    height: 36px !important;
    vertical-align: middle;
  }
  .el-button--default:first-child i,
  .el-button--default:last-child i {
    font-size: 14px;
  }

  .el-button--default span {
    font-size: 14px !important;
  }

  .el-select-dropdown__wrap {
    margin-bottom: 0px !important;
  }

  .el-table__body td {
    padding-top: 10px !important;
    padding-bottom: 10px !important;
  }

  .el-button {
    margin-left: 0px !important;
    margin-right: 10px;
  }
</style>
